<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 게시판 컨트롤러
 */
class Bbs extends CI_Controller {
	
	var $data = array();
	
	function __construct() {
		parent::__construct();
		$this->data['sess_userinfo'] = $this->session->userdata('userinfo');

		$this->load->model('bbs/Bbs_model', 'bbs');
		
		$this->load->helper(array('form', 'url'));
		$this->load->helper(array('pagenavi'));
	}

	/**
	 * 
	 */
	function _remap() {
		log_message('debug', "@@@@ Bbs::_remap()");

		// 파라미터 값으로 서비스 구분
		$cate   = $this->uri->segment(2); // 후기, 자유 등
		$method = $this->uri->segment(3);	// write, read, list 등
		
		log_message('debug', "@@ cate=$cate");
		log_message('debug', "@@ method=$method");

		//---------------------------------------------------------
		// 회원 사진 및 요약 정보
		//---------------------------------------------------------
		$this->load->model('mypage/Member_model', 'member', TRUE);
		$data['summary'] = $this->member->get_summary($this->data['sess_userinfo']['user_id']);
		$this->data['INC_MEMBER'] = $this->load->view('inc/member_v', $data, TRUE);

		// 비회원은 글쓰기, 덧글쓰기를 못하게 한다.
		if ($this->data['sess_userinfo']['user_id'] == 'guests') {
			if (!empty($method) && $method != 'list' && $method != 'read') {
				echo "<script type='text/javascript'>";
				echo "	alert('로그인 후에 등록하실 수 있습니다.');";
				echo "	history.back();";
				echo "</script>";
				return;
			}
		}
		
		$this->data['cate'] = $cate;
		if ($cate == 'postscript') {
			$this->data['category_title'] = '운신이용후기';
		} elseif ($cate == 'free') {
			$this->data['category_title'] = '자유게시판';
		} elseif ($cate == 'starpt') {
			$this->data['category_title'] = '사진으로 보는 스타 운세';
		} elseif ($cate == 'notice') {
			$this->data['category_title'] = '공지사항';
		} elseif ($cate == 'faq') {
			$this->data['category_title'] = '자주하는 질문';
		} elseif ($cate == 'event') {
			$this->data['category_title'] = '전체 이벤트';
		} elseif ($cate == 'event_notice') {
			$this->data['category_title'] = '행운의 당첨자';
		} elseif ($cate == 'qna') {
			$this->data['category_title'] = '1:1 문의하기';
		}
		
		
		if (empty($method) || $method == 'list') {
			$this->_list($cate);
		} elseif ($method == 'read') {
			$this->_read($cate);
		} elseif ($method == 'write') {
			$this->_write($cate);
		} elseif ($method == 'write_ok') {
			$this->_write_ok($cate);
		} elseif ($method == 'modify') {
			$this->_modify($cate);
		} elseif ($method == 'modify_ok') {
			$this->_modify_ok($cate);
		} elseif ($method == 'reply_ok') {
			$this->_reply_ok($cate);
		} elseif ($method == 'remove_ok') {
			$this->_remove_ok($cate);
		} elseif ($method == 'remove_reply_ok') {
			$this->_remove_reply_ok($cate);
		} elseif ($method == 'recommend_ok') {
			$this->_recommend_ok();
		} else {
			show_404();
		}
	}

	/**
	 * 글내용 보기
	 */
	function _read($cate) {
		log_message('debug', "@@@@ Bbs::_read($cate)");

		if ($cate == 'qna') {
			die("접근할수 없습니다.");
		}
		
		$search_type    = $this->input->get('search_type', TRUE);
		$search_keyword = $this->input->get('search_keyword', TRUE);
		$page           = $this->input->get('page', TRUE);
		$search_type    = empty($search_type) ? '' : $search_type;
		$search_keyword = empty($search_keyword) ? '' : $search_keyword;

		// 목록으로 가기 URL
		$this->data['list_url'] = "/bbs/$cate?search_type=$search_type&search_keyword=$search_keyword&page=$page";
		
		// 이전, 다음글 URL
		$this->data['read_url'] = "/bbs/$cate/read?search_type=$search_type&search_keyword=$search_keyword&page=$page&idx=";

		// 댓글 액션 URL
		$this->data['action_url'] = "/bbs/$cate/reply_ok";
		
		$idx  = $this->input->get('idx', TRUE);

		// 수정, 삭제 URL
		$this->data['modify_url'] = "/bbs/$cate/modify?idx=$idx";
		$this->data['remove_url'] = "/bbs/$cate/remove_ok?idx=$idx";
		$this->data['remove_reply_url'] = "/bbs/$cate/remove_reply_ok?idx=$idx";

		// 조회수 업데이트
		$this->bbs->update_bbs_hit($idx);
		
		// 글 내용 가져오기
		$this->data['content'] = $this->bbs->get_bbs_content($cate, $idx);
		
		if (empty($this->data['content'])) {
			die("글이 없습니다.");
		}
		
		// 이전, 다음글
		$this->data['prev_content'] = $this->bbs->get_bbs_side_content($cate, $idx, 'prev');
		$this->data['next_content'] = $this->bbs->get_bbs_side_content($cate, $idx, 'next');
		
		// 댓글 리스트
		$this->data['reply_list'] = $this->bbs->select_bbs_reply_list($idx);
				
		if ($cate == 'notice' || $cate == 'faq' || $cate == 'qna') {
			$this->load->view('cs/notice_read_v', $this->data);
		} elseif ($cate == 'event' || $cate == 'event_notice') {
			$this->load->view('event/read_v', $this->data);
		} elseif ($cate == 'starpt') {
			$this->load->model('unse/Star_model', 'star');
			$this->data['artist'] = $this->star->get_artist($this->data['content']['artist_idx']);
			$this->load->view('bbs/starpt_read_v', $this->data);
		} else {
			$this->load->view('bbs/read_v', $this->data);
		}
	}
	
	/**
	 * 리스트
	 */
	function _list($cate) {
		log_message('debug', "@@@@ Bbs::_list($cate)");

		$search_type    = $this->input->get('search_type', TRUE);
		$search_keyword = $this->input->get('search_keyword', TRUE);
		$page           = $this->input->get('page', TRUE);

		$search_type    = empty($search_type) ? '' : $search_type;
		$search_keyword = empty($search_keyword) ? '' : $search_keyword;
		$current_page   = empty($page) ? 1 : $page;

		$page_size  = BBS_PAGE_SIZE;		// 한 페이지에 보여줄 글 수
		$block_size = BBS_BLOCK_SIZE;	// 네비영역의 한 블록에 보여줄 페이지 수

		$total_cnt  = $this->bbs->get_bbs_total_count($cate, 'N', 'N', $search_type, $search_keyword);	// 총 글 수

		$this->data['list'] = $this->bbs->select_bbs_list($cate, 'N', 'N', $search_type, $search_keyword, $current_page, $page_size);
		$this->data['notice_list'] = $this->bbs->select_bbs_list($cate, 'N', 'Y', $search_type, $search_keyword, 1, 3);
		$this->data['best_list'] = $this->bbs->select_bbs_list($cate, 'Y', 'N', $search_type, $search_keyword, 1, 3);
		$this->data['rownum'] = $total_cnt-(($current_page-1)*$page_size);

		$uri = $this->uri->uri_string()."?search_type=$search_type&search_keyword=$search_keyword";
		$this->data['navi'] = page_navigation($current_page, $total_cnt, $page_size, $block_size, $uri);
		
		// 검색 URL (뷰단에서 SCRIPT_NAME이 먹질 않아서 여기에서 셋팅한다.)
		$this->data['uri'] = '/'.$this->uri->uri_string();
		
		// 내용 보기 URL
		$this->data['read_url'] = "/bbs/$cate/read?search_type=$search_type&search_keyword=$search_keyword&page=$page&idx=";
		
		if ($cate == 'notice' || $cate == 'faq') {
			$this->load->view('cs/notice_list_v', $this->data);
		} elseif ($cate == 'event' || $cate == 'event_notice') {
			$this->load->view('event/list_v', $this->data);
		} elseif ($cate == 'qna') {
			redirect("/mypage/qna_history");
		} else {
			$this->load->view('bbs/list_v', $this->data);
		}
	}
	
	/**
	 * 글쓰기 폼
	 */
	function _write($cate) {
		log_message('debug', "@@@@ Bbs::_write()");
		
		if ($cate == 'notice') {
			if ($this->data['sess_userinfo']['user_id'] == 'unsin1') {
				$this->load->view('cs/notice_write_v', $this->data);
				return;
			}
		} elseif ($cate == 'qna') {
			$this->load->view('cs/qna_write_v', $this->data);
		} else {
			$this->load->view('bbs/write_v', $this->data);
		}
	}
	
	/**
	 * 글쓰기 완료
	 */
	function _write_ok($cate) {
		log_message('debug', "@@@@ Bbs::_write_ok($cate)");
		
		// 파일 저장 
		$result_upload = $this->_do_upload($cate);
		log_message('debug', "@@ result_upload=".print_r($result_upload, TRUE));
		
		// 글 저장 (파일이 성공적으로 저장됐을때만 글 저장)
		$bbs_content['category']   = $cate;
		$bbs_content['user_id']    = $this->data['sess_userinfo']['user_id'];
		$bbs_content['nickname']   = $this->data['sess_userinfo']['nickname'];
		$bbs_content['service_id'] = $this->input->post('service_id', TRUE);
		$bbs_content['service_id'] = empty($bbs_content['service_id']) ? '' : $bbs_content['service_id'];
		$bbs_content['subject']    = $this->input->post('subject', TRUE);
		$bbs_content['content']    = $this->input->post('content', TRUE);

		$this->bbs->save_bbs($bbs_content, $result_upload);

		if ($cate != 'qna') {
			$this->load->model('point/Point_model', 'point_model', TRUE);
			$this->point_model->update_activity_point($this->data['sess_userinfo']['user_id'], 'WRITE');
		}
		
		if ($cate == 'qna') {
			// 관리자에게 이메일 발송
			$this->_send_qna_email($bbs_content);
		}

		redirect("/bbs/$cate/");
	}

	/**
	 * 1:1문의 메일 관리자에게 발송
	 */
	function _send_qna_email($bbs_content) {
		log_message('debug',"#### Bbs_model::_send_qna_email($bbs_content)");
		
		$params['to_email'] = ADMIN_EMAIL;
		$params['user_id']  = $bbs_content['user_id'];
		$params['subject']  = $bbs_content['subject'];

		$url = SSL_ROOT_URL."/external/xpm4/mail-qna.php";
		$req = new HttpRequest($url, HttpRequest::METH_POST);
		$req->addPostFields($params);

		try {
			$return_obj = $req->send()->getBody();
			$this->logsql->log_result($return_obj);
			return TRUE;
		} catch (HttpException $ex) {
			log_message('error','## 이메일 발송 중 에러 발생');
			echo $ex;
			return FALSE;
		}
	}
	
	/**
	 * 파일 업로드
	 */
	function _do_upload($cate) {
		log_message('debug', "@@@@ Change::_do_upload($cate)");
		
		$target_dir = FILE_UPLOAD_DIR.$cate."/".date('Ym',time());
		$target_url = FILE_UPLOAD_URL.'/'.$cate."/".date('Ym',time());
		log_message('debug','@@ target_dir='.$target_dir);
		
		if(!is_dir($target_dir)){
		   mkdir($target_dir, DIR_WRITE_MODE);
		}
		
		$config['upload_path']   = $target_dir;
		$config['allowed_types'] = 'gif|jpg';
		$config['max_filename']  = '255';
		$config['max_size']      = '1024';
		$config['max_width']     = '1920';
		$config['max_height']    = '1080';
		$config['encrypt_name']  = TRUE;
		$config['remove_spaces'] = TRUE;
		
		$this->load->library('upload', $config);
		
		if ( ! $this->upload->do_upload()) {
			$result = $this->upload->display_errors();
			log_message('error','@@ _do_upload error='.$result);
			log_message('error','@@ _do_upload error_msg='.print_r($this->upload->error_msg,TRUE));
			if ($this->upload->error_msg[0] == 'The image you are attempting to upload exceedes the maximum height or width.') {
				echo "<script type='text/javascript'>";
				echo "	alert('첨부한 이미지의 해상도가 큽니다.');";
				echo "	history.back();";
				echo "</script>";
				exit;
			} elseif ($this->upload->error_msg[0] == 'The file you are attempting to upload is larger than the permitted size.') {
				echo "<script type='text/javascript'>";
				echo "	alert('첨부한 이미지의 파일용량이 큽니다.');";
				echo "	history.back();";
				echo "</script>";
				exit;
			} elseif ($this->upload->error_msg[0] == 'You did not select a file to upload.') {
				return '';
			} else {
				echo "<script type='text/javascript'>";
				echo "	alert('업로드 실패');";
				echo "	history.back();";
				echo "</script>";
				exit;
			}
		}
		
		$result = $this->upload->data();
		$result['file_url'] = $target_url.'/'.$result['file_name'];
		log_message('debug','@@ _do_upload data='.print_r($result,TRUE));
		
		return $result;
	}
	
	/**
	 * 글 수정 폼
	 */
	function _modify($cate) {
		log_message('debug', "@@@@ Bbs::_modify()");
		
		$idx  = $this->input->get('idx', TRUE);
		
		$this->data['content'] = $this->bbs->get_bbs_content($cate, $idx);
		
		// 본인 여부 확인
		if ($this->data['content']['user_id'] != $this->data['sess_userinfo']['user_id']) {
			die('본인의 글이 아닙니다.');
		}
		
		$this->load->view('bbs/modify_v', $this->data);
	}
	
	/**
	 * 글 수정 완료
	 */
	function _modify_ok($cate) {
		log_message('debug', "@@@@ Bbs::_modify_ok($cate)");
		
		// 파일 저장 
		$result_upload = $this->_do_upload($cate);
		
		// 글 저장 (파일이 성공적으로 저장됐을때만 글 저장)
		$bbs_content['idx']        = $this->input->post('idx', TRUE);
		$bbs_content['category']   = $cate;
		$bbs_content['user_id']    = $this->data['sess_userinfo']['user_id'];
		$bbs_content['nickname']   = $this->data['sess_userinfo']['nickname'];
		$bbs_content['service_id'] = $this->input->post('service_id', TRUE);
		$bbs_content['subject']    = $this->input->post('subject', TRUE);
		$bbs_content['content']    = $this->input->post('content', TRUE);

		$this->bbs->modify_bbs($bbs_content, $result_upload);

		redirect("/bbs/$cate/read?idx=".$bbs_content['idx']);
	}

	
	/**
	 * 삭제
	 */
	function _remove_ok($cate) {
		log_message('debug', "@@@@ Bbs::_remove_ok()");
		
		$idx = $this->input->get('idx', TRUE);
		
		// 본인확인
		$writer_id = $this->bbs->get_bbs_column_value($idx, 'user_id');
		if ($writer_id == '') {
			die('해당하는 글이 없습니다.');
		}
		if ($writer_id != $this->data['sess_userinfo']['user_id']) {
			die('본인의 글이 아닙니다.');
		}
		
		// 글 삭제
		$result = $this->bbs->remove_bbs($idx);
		if ($result == FALSE) {
			echo "<script type='text/javascript'>";
			echo "alert('삭제 실패');";
			echo "history.back();";
			echo "</script>";
			return;
		}
		
		redirect("/bbs/$cate");
	}
	
	/**
	 * 댓글 삭제
	 */
	function _remove_reply_ok($cate) {
		log_message('debug', "@@@@ Bbs::_remove_reply_ok($cate)");
		
		$seq = $this->input->get('seq', TRUE);
		$idx = $this->input->get('idx', TRUE);
		
		// 본인확인
		$writer_id = $this->bbs->get_bbs_reply_column_value($seq, 'user_id');
		if ($writer_id == '') {
			die('해당하는 덧글이 없습니다.');
		}
		if ($writer_id != $this->data['sess_userinfo']['user_id']) {
			die('본인의 덧글이 아닙니다.');
		}
		
		// 글 삭제
		$this->bbs->delete_bbs_reply($seq);
		
		redirect("/bbs/$cate/read?idx=".$idx);
	}
	
	/**
	 * 댓글 쓰기 완료
	 */
	function _reply_ok($cate) {
		log_message('debug', "@@@@ Bbs::_reply_ok()");
		
		// 글 저장 (파일이 성공적으로 저장됐을때만 글 저장)
		$bbs_reply['user_id']  = $this->data['sess_userinfo']['user_id'];
		$bbs_reply['nickname'] = $this->data['sess_userinfo']['nickname'];
		$bbs_reply['idx']      = $this->input->post('idx', TRUE);
		$bbs_reply['content']  = $this->input->post('content', TRUE);

		$this->bbs->insert_bbs_reply($bbs_reply);

		$this->load->model('point/Point_model', 'point_model', TRUE);
		$this->point_model->update_activity_point($this->data['sess_userinfo']['user_id'], 'REPLY');
		
		redirect("/bbs/$cate/read?idx=".$bbs_reply['idx']);
	}
	
	/**
	 * 공감하기 (AJAX)
	 */
	function _recommend_ok() {
		log_message('debug', "@@@@ Bbs::_recommend_ok()");
		
		$idx      = $this->input->get('idx', TRUE);
		$user_id  = $this->data['sess_userinfo']['user_id'];

		// 이미 추천했는지 검사
		$recommend_user = $this->bbs->get_bbs_column_value($idx, 'recommend_user');
		if (preg_match("/$user_id/", $recommend_user)) {
			echo "이미 공감하였습니다.";
			exit;
		}

		// 추천수 업데이트
		$result = $this->bbs->update_bbs_recommend($idx, $user_id);
		if ($result == TRUE) {
			echo $this->bbs->get_bbs_column_value($idx, 'recommend');
		} else {
			echo "false";
		}
		exit;
	}
}

/* End of file bbs.php */
/* Location: ./application/controllers/bbs.php */